package com.yehuishou.controller;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.ietf.jgss.Oid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import com.yehuishou.pojo.Order;
import com.yehuishou.pojo.Zulinorder;
import com.yehuishou.service.AssessmentValueService;
import com.yehuishou.service.LeaseItemService;
import com.yehuishou.service.SaleOrderService;
import com.yehuishou.weixin_pay.IpAddressGet;
import com.yehuishou.weixin_pay.MyWXPayUtil;
import com.yehuishou.weixin_pay.QrcodeCreate;
import com.yehuishou.weixin_pay.WxConfig;

/**
 * 
 * @author xiaosa
 * @className OrderPayController.java
 * @descripe 订单支付的控制器
 * @data 2018年6月12日
 */

@Controller
public class WxPayController {

	@Autowired
	private SaleOrderService saleOrderService;
	@Autowired
	private LeaseItemService liser;

	/**
	 * @param 1.商品的id
	 *            2.订单号 3.订单金额
	 * @throws Exception
	 */
	@RequestMapping("/WxPay") // 用户选择微信支付
	public String getOrderinfo(HttpServletRequest req, //
			String oid, String payment// 1.订单号
	) throws Exception {
		// String itemid="23424242";// 2.商品的id
		// String payment="88";// 3.支付金额
		// 沙箱环境
		// boolean useSandbox =true;
		// 1.获取支付订单号

		// 2 获取当前操作用户的ip
		String ipAddress = IpAddressGet.getIpAddr(req);

		String code_url = "";
		WxConfig config = new WxConfig();
		// 生产环境
		WXPay wxpay = new WXPay(config);

		// WXPay wxpay = new WXPay(config,SignType.MD5, useSandbox);
		Map<String, String> data = new HashMap<String, String>();
		data.put("body", "耶回收官方商城");// 商品描述
		data.put("out_trade_no", oid);// 商户的订单号
		data.put("device_info", "WEB");// 设备号pc 端填写web
		data.put("fee_type", "CNY");// 标价币种 此处是人民币CNY
		data.put("total_fee", payment);// 标价金额 int 88
		data.put("spbill_create_ip", ipAddress);// 终端ip（用户的ip）
		data.put("notify_url", "http://www.yehuishou.com/wx/notify");// 通知地址
		data.put("trade_type", "NATIVE"); // 交易类型 此处指定为扫码支付
		// data.put("product_id",itemid );//商品的id
		// 微信支付下单请求

		Map<String, String> resp = wxpay.unifiedOrder(data);
		System.out.println(resp);
		code_url = resp.get("code_url");
		Double pays = Double.parseDouble(payment)*0.01;
		req.setAttribute("orderid", oid);
		req.setAttribute("price", pays);
		req.setAttribute("code_url", code_url);

		// 返回订单号 应付金额 二维码的code_url
		return "weixin";// 跳转到微信支付 二维码展示页面
	}

	/*
	 * @RequestMapping("/toQrcode") public String toQrcode(HttpServletRequest req) {
	 * 
	 * return "weixin"; }
	 */

	// 二维码图片流 直接 不存储 直接读取到页面
	@ResponseBody
	@RequestMapping("/getQRCode")
	public String getQrcode(String code_url, HttpServletResponse resp) {
		// 生成图片 将图片流发到前台网页
		QrcodeCreate.encodeQrcode(code_url, resp);
		return "weixin";
	}

	// 微信支付结果的回调通知
	@SuppressWarnings("unchecked")
	@RequestMapping("/wx/notify")
	public void getWeixinNotify(HttpServletRequest req, HttpServletResponse res) {

		try { // 读取参数
			InputStream inputStream;
			StringBuffer sb = new StringBuffer();
			inputStream = req.getInputStream();
			String s;
			BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
			while ((s = in.readLine()) != null) {
				sb.append(s);
			}
			in.close();
			inputStream.close();

			// 解析xml成map
			Map<String, String> m = new HashMap<String, String>();
			m = WXPayUtil.xmlToMap(sb.toString());

			// 过滤空 设置 TreeMap
			SortedMap<String, String> packageParams = new TreeMap<String, String>();
			Iterator<String> it = m.keySet().iterator();
			while (it.hasNext()) {
				String parameter = (String) it.next();
				String parameterValue = m.get(parameter);

				String v = "";
				if (null != parameterValue) {
					v = parameterValue.trim();
				}
				packageParams.put(parameter, v);
			}

			// 账号信息
			WxConfig Wx = new WxConfig();
			String key = Wx.getKey();
			String out_trade_no = packageParams.get("out_trade_no");
			// logger.info(packageParams);

			// 判断签名是否正确(安全验证)
			if (MyWXPayUtil.isSignatureValid(packageParams, key)) {
				String resXml = ""; // 定义需要返回给微信服务器的xml数据

				// 判断微信服务器返回的状态码 为SUCCESS时 支付成功！
				if ("SUCCESS".equals((String) packageParams.get("result_code"))) {

					////////// 执行自己的业务逻辑////////////////
					String mch_id = (String) packageParams.get("mch_id");
					String openid = (String) packageParams.get("openid");
					String is_subscribe = (String) packageParams.get("is_subscribe");

					String bank_type = (String) packageParams.get("bank_type");
					String total_fee = (String) packageParams.get("total_fee");
					String transaction_id = (String) packageParams.get("transaction_id");

					System.out.println("mch_id:" + mch_id);
					System.out.println("openid:" + openid);
					System.out.println("is_subscribe:" + is_subscribe);
					System.out.println("out_trade_no:" + out_trade_no);
					System.out.println("total_fee:" + total_fee);
					System.out.println("bank_type:" + bank_type);
					System.out.println("transaction_id:" + transaction_id);

					// 查询数据库查询订单的支付状态和支付金额
					Order order = saleOrderService.selpayorder(out_trade_no).get(0);
					Double payment = order.getPayment();
					String pm = (payment * 100) + "";

					// 判断订单是否已经支付
					if (order.getStatus() != 2) {// 未支付
						order.setStatus(2);
						saleOrderService.assess(order); // 设置订单状态支付成功

						// 若订单为租赁订单
						if (order.getOrder_type() == 3) {
							Zulinorder zlo = liser.findByZL(out_trade_no);
							Date d = new Date();
							String time = zlo.getTime();
							Calendar cal = Calendar.getInstance();
							cal.setTime(d);
							int i = time.length();
							if (time.endsWith("天")) {
								String sub = time.substring(0, i - 1);
								Integer s1 = Integer.parseInt(sub);
								cal.add(Calendar.DATE, s1);
								zlo.setGhtime(cal.getTime());
							} else {
								String sub = time.substring(0, i - 2);
								Integer s1 = Integer.parseInt(sub);
								cal.add(Calendar.MONTH, s1);
								zlo.setGhtime(cal.getTime());
							}
							zlo.setGhm(1);
							liser.update(zlo);
						}else if (order.getOrder_type()==2) {
							saleOrderService.stocknumdown(order);
						}

					} else {// 已支付
						System.out.println("用户重复支付！");

					}

					// 支付金额与订单一致
					if (total_fee.equals(pm)) {

						resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
								+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";

					} else {

						// 用户支付的金额和订单的金额不一致
						resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
								+ "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";

					}

					// 修改订单的支付状态为已经支付
					// 成功回调后需要处理预生成订单的状态和一些支付信息
					// 查询数据库中订单，首先判定订单中金额与返回的金额是否相等，不等金额被纂改
					// 判定订单是否已经被支付，不可重复支付
					// 正常处理相关业务逻辑

				} else {
					System.out.println("支付失败,错误信息：" + packageParams.get("err_code") + "-----订单号：：：" + out_trade_no
							+ "*******支付失败时间：：：：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

					String err_code = (String) packageParams.get("err_code");

					resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
							+ "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";

				}
				// ------------------------------
				// 处理业务完毕
				// ------------------------------
				BufferedOutputStream out = new BufferedOutputStream(res.getOutputStream());
				out.write(resXml.getBytes());
				out.flush();
				out.close();

			} else {
				System.out
						.println("通知签名验证失败---时间::::" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block

		}

	}

	// 查询订单的状态 微信支付页面
	@ResponseBody
	@RequestMapping("/getOrdereStatus")
	public boolean getOrdereStatus(String oid) {
		// Map<String , Object> map = new HashMap<>();
		boolean rs = false;
		// 订单的状态为2 为已支付
		
		//微信订单查询
		 WxConfig config = new WxConfig();
	        WXPay wxpay=null;
			try {
				wxpay = new WXPay(config);
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

	        Map<String, String> data = new HashMap<String, String>();
	        data.put("out_trade_no",oid);

	        
	        Map<String, String> resp=null;
	        try {
	             resp = wxpay.orderQuery(data);
	            System.out.println(resp);
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	        
	        //返回码成功！
	       if(resp.get("return_code").equals("SUCCESS")) {
	    	   
	    	   //支付成功
	    	  if(resp.get("trade_state").equals("SUCCESS")) {
	    		  
	    		  rs=true;    
	    	  }    
	       }  
	       //查询自己的服务器
		/*if ((saleOrderService.selpayorder(oid).get(0).getStatus() == 2)) {

			rs = true;
		}*/
		return rs;
	}

}
